﻿using Awaken.Utils.CacheProvider;
using Awaken.Utils.WidgetCode;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;

namespace Awaken.MessageProvider
{
	/// <summary>
	/// 验证码缓存中心
	/// </summary>
	public class ParityCodeCache
	{
		private const string KEY_PREFIX = "vcode_";

		private static volatile ParityCodeCache _instance;

		private static readonly object _locker = new object();		

		private ParityCodeCache()
		{
			
		}

		public static ParityCodeCache Instance
		{
			get
			{
				if (_instance == null)
				{
					lock (_locker)
					{
						if (_instance == null)
						{
							_instance = new ParityCodeCache();
						}
					}
				}

				return _instance;
			}
		}

		public string Read(string name)
		{
			ICacheProvider cacheProvider = MemoryCacheProvider.GetInstance();

			var key = KEY_PREFIX + name;

			if (cacheProvider.Contains(key))
			{
				var code = cacheProvider.Get<string>(key);

				return code;
			}

			return string.Empty;

		}

		public bool ValidKey(string keyName)
		{
			ICacheProvider cacheProvider = MemoryCacheProvider.GetInstance();

			var key = KEY_PREFIX + keyName;

			return cacheProvider.Contains(key);			
		}

		public void Update(string name, string code, CacheItemPolicy policy)
		{
			ICacheProvider cacheProvider = MemoryCacheProvider.GetInstance();

			var key = KEY_PREFIX + name;

			cacheProvider.Update(key,code,policy);				
			

		}

		public void Remove(string name)
		{
			ICacheProvider cacheProvider = MemoryCacheProvider.GetInstance();

			var key = KEY_PREFIX + name;

			cacheProvider.Remove(key);

		}

		/// <summary>
		/// 统计次数
		/// </summary>
		/// <param name="name"></param>
		/// <returns></returns>
		public int Count(string name)
		{
			ICacheProvider cacheProvider = MemoryCacheProvider.GetInstance();

			var key = string.Format("{0}{1}{2}", KEY_PREFIX , name,DateTime.Today.ToString("yyMMdd"));

			int times = 0;

			if (cacheProvider.Contains(key))
			{
				times = cacheProvider.Get<int>(key);
			}

			var policy = new CacheItemPolicy()
			{
				AbsoluteExpiration = DateTime.Now.AddMinutes(59)
			};

			//统计次数+1
			cacheProvider.Update(key, times + 1, policy);
			
			return times;

		}
	}
}
